using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace TestCases.Utils
{
    public static class XmlSerializationUtils
    {
        public static string Serialize<TObject>(this TObject value)
        {
            var output = new StringBuilder();
            new XmlSerializer(typeof(TObject)).Serialize(new StringWriter(output), value);
            return output.ToString();
        }
        

        public static TObject Deserialize<TObject>(this string xml)
        {
            return (TObject) new XmlSerializer(typeof(TObject)).Deserialize(new StringReader(xml));
        }


        public static string GetNamespace(this object obj)
        {
            return GetNamespace(obj.GetType());
        }

        public static string GetNamespace(Type type)
        {
            var attributes = type.GetCustomAttributes(typeof(XmlRootAttribute), false);
            return attributes.Length > 0 ? ((XmlRootAttribute) attributes[0]).Namespace : null;
        }
    }
}